//
//  Tool.m
//  适配
//
//  Created by 孙海琛 on 16/4/15.
//  Copyright © 2016年 tiannu. All rights reserved.
//

#import "Tool.h"
#include <net/if.h>
#include <ifaddrs.h>
#include <net/if_dl.h>
//#import "LoginController.h"

@interface Tool()<UIActionSheetDelegate>

@property (nonatomic,strong) NSMutableArray *maps;

@end

@implementation Tool

- (NSMutableArray *)maps
{
    if (!_maps) {
        _maps = [NSMutableArray array];
    }
    return _maps;
}


+ (instancetype)shareTool {
    static Tool *tool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[self alloc] init];
    });
    return tool;
}


+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

//做ios版本之间的适配
//不同的ios版本,调用不同的方法,实现相同的功能
+(CGSize)sizeOfStr:(NSString *)str andFont:(UIFont *)font andMaxSize:(CGSize)size andLineBreakMode:(NSLineBreakMode)mode
{
//    NSLog(@"版本号:%f",[[[UIDevice currentDevice]systemVersion]doubleValue]);
    CGSize s;
    if ([[[UIDevice currentDevice]systemVersion]doubleValue]>=7.0) {
//        NSLog(@"ios7以后版本");
//        NSDictionary *dic=@{NSFontAttributeName:font};
        NSMutableDictionary  *mdic=[NSMutableDictionary dictionary];
        [mdic setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
        [mdic setObject:font forKey:NSFontAttributeName];
        s = [str boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                           attributes:mdic context:nil].size;
    }
    else
    {
//        NSLog(@"ios7之前版本");
        s=[str sizeWithFont:font constrainedToSize:size lineBreakMode:mode];
    }
    return s;
}
//计算可变NSMutableAttributedString字符串高度
+(CGSize)sizeOfStrArt:(NSMutableAttributedString *)str andFont:(CGFloat)font andMaxSizeWidth:(NSInteger)widths lineSpacing:(float)line
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    
    paragraphStyle.lineSpacing = line;  // 段落高度
    
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font] range:NSMakeRange(0, str.length)];
    [str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, str.length)];
    
    CGSize attSize = [str boundingRectWithSize:CGSizeMake(widths, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    return attSize;
}
//解决网址里面有中文的情况
+(NSString *)stringFromChURL:(NSString *)str
{
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, NULL,  kCFStringEncodingUTF8 ));
}

+ (NSString*)getCurrentDeviceModel
{
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G (A1203)";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G (A1241/A1324)";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS (A1303/A1325)";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (A1349)";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S (A1387/A1431)";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (A1456/A1532)";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    
    return platform;
    
}
+ (instancetype )dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    id  dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
//去除多余分割线
+ (void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}
// 将字典或者数组转化为JSON串
+ (NSString *)toJSONData:(id)theData{
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                 encoding:NSUTF8StringEncoding];
    
    if (error){
         NSLog(@"json解析失败：%@",error);
        return nil;
    }
    return jsonString;
}
+(NSDictionary*)getObjectData:(id)obj
{
    NSMutableDictionary
    *dic = [NSMutableDictionary dictionary];
    
    unsigned
    int propsCount;
    
    objc_property_t
    *props = class_copyPropertyList([obj class], &propsCount);
    
    for(int
        i = 0;i < propsCount; i++)
        
    {
        
        objc_property_t
        prop = props[i];
        
        NSString
        *propName = [NSString stringWithUTF8String:property_getName(prop)];
        
        id
        value = [obj valueForKey:propName];
        
        if(value
           == nil)
            
        {
            
            value
            = [NSNull null];
            
        }
        
        else
            
        {
            
            value= [self getObjectInternal:value];
            
        }
        
        [dic
         setObject:value forKey:propName];
        
    }
    
    return
    
    dic;
}
+
(id)getObjectInternal:(id)obj

{
    
    if([obj
        isKindOfClass:[NSString class]]
       ||
       [obj isKindOfClass:[NSNumber class]]
       ||
       [obj isKindOfClass:[NSNull class]])
    {
        return
        obj;
    }
    
    
    
    if([obj
        isKindOfClass:[NSArray class]])
        
    {
        
        NSArray
        *objarr = obj;
        
        NSMutableArray
        *arr = [NSMutableArray arrayWithCapacity:objarr.count];
        
        for(int
            i = 0;i < objarr.count; i++)
            
        {
            
            [arr
             setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
            
        }
        
        return
        
        arr;
        
    }
    
    
    
    if([obj
        isKindOfClass:[NSDictionary class]])
        
    {
        
        NSDictionary
        *objdic = obj;
        
        NSMutableDictionary
        *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
        
        for(NSString
            *key in
            
            objdic.allKeys)
            
        {
            
            [dic
             setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
            
        }     
        
        return
        
        dic;
        
    } 
    
    return
    
    [self getObjectData:obj];
    
}
/*
 *判断是否连网
 *返回值:yes 以连网
 *      no  未连网
 */
+(BOOL) connectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }
    
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    return (isReachable && !needsConnection) ? YES : NO;
}
+(NSString *)gainDate
{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentTime = [formatter stringFromDate:[NSDate date]];
    return currentTime;
}
+(NSString *)zhDate:(NSString *)strDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yy-MM-dd HH:mm:ss"];
    NSDate *nowDate = [formatter dateFromString:strDate];
    NSTimeInterval newTime = [nowDate timeIntervalSince1970];
    return [NSString stringWithFormat:@"%ld",(long)newTime];
}
+(id)jsonFile:(NSString *)fileName
{
    NSError*error;
    NSString *filePath = [[NSBundle mainBundle]pathForResource:fileName ofType:@"json"];
    NSData *data=[NSData dataWithContentsOfFile:filePath];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    return jsonObject;
}
+(NSString *)jsonFileID:(NSString *)address
{
    NSError*error;
    NSString *filePath = [[NSBundle mainBundle]pathForResource:address ofType:@"json"];
    NSData *data=[NSData dataWithContentsOfFile:filePath];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                 encoding:NSUTF8StringEncoding];
    if (error){
        NSLog(@"json解析失败：%@",error);
        return nil;
    }
    return jsonString;
}

//- (NSString *)isEqueHttp
//{
////    AppDelegate *appDele = [UIApplication sharedApplication].delegate;
////    NSString *strID = appDele.strHttp;
////    return strID;
//}
+ (UIImage *) imageFromURLString: (NSString *) urlstring
{
    return [UIImage imageWithData:[NSData
                                   dataWithContentsOfURL:[NSURL URLWithString:urlstring]]];
}

+ (float)folderSizeAtPath:(NSString *)path
{
    //定义变量存储总的缓存大小
    long long sumSize = 0;
    //01.获取当前图片缓存路径
    NSString *cacheFilePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    cacheFilePath = [cacheFilePath stringByAppendingPathComponent:path];
    //02.创建文件管理对象
    NSFileManager *filemanager = [NSFileManager defaultManager];
    //获取当前缓存路径下的所有子路径
    NSArray *subPaths = [filemanager subpathsOfDirectoryAtPath:cacheFilePath error:nil];
    //遍历所有子文件
    for (NSString *subPath in subPaths) {
        //1）.拼接完整路径
        NSString *filePath = [cacheFilePath stringByAppendingFormat:@"/%@",subPath];
        //2）.计算文件的大小
        long long fileSize = [[filemanager attributesOfItemAtPath:filePath error:nil]fileSize];
        //3）.加载到文件的大小
        sumSize += fileSize;
    }
    float size_m = sumSize/(1000*1000);
    return size_m;
}

+(NSString *)versionIndex
{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    return version;
}
//获取流量信息
+ (NSArray *)getDataCounters
{
    BOOL   success;
    struct ifaddrs *addrs;
    const struct ifaddrs *cursor;
    const struct if_data *networkStatisc;
    
    int WiFiSent = 0;
    int WiFiReceived = 0;
    int WWANSent = 0;
    int WWANReceived = 0;
    
    NSString *name;
    
    success = getifaddrs(&addrs) == 0;
    if (success)
    {
        cursor = addrs;
        while (cursor != NULL)
        {
            name=[NSString stringWithFormat:@"%s",cursor->ifa_name];
            NSLog(@"ifa_name %s == %@\n", cursor->ifa_name,name);
            // names of interfaces: en0 is WiFi ,pdp_ip0 is WWAN
            if (cursor->ifa_addr->sa_family == AF_LINK)
            {
                if ([name hasPrefix:@"en"])
                {
                    networkStatisc = (const struct if_data *) cursor->ifa_data;
                    WiFiSent+=networkStatisc->ifi_obytes;
                    WiFiReceived+=networkStatisc->ifi_ibytes;
                    NSLog(@"WiFiSent %d ==%d",WiFiSent,networkStatisc->ifi_obytes);
                    NSLog(@"WiFiReceived %d ==%d",WiFiReceived,networkStatisc->ifi_ibytes);
                }
                if ([name hasPrefix:@"pdp_ip"])
                {
                    networkStatisc = (const struct if_data *) cursor->ifa_data;
                    WWANSent+=networkStatisc->ifi_obytes;
                    WWANReceived+=networkStatisc->ifi_ibytes;
                    NSLog(@"WWANSent %d ==%d",WWANSent,networkStatisc->ifi_obytes);
                    NSLog(@"WWANReceived %d ==%d",WWANReceived,networkStatisc->ifi_ibytes);
                }
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return [NSArray arrayWithObjects:[NSNumber numberWithInt:WiFiSent], [NSNumber numberWithInt:WiFiReceived],[NSNumber numberWithInt:WWANSent],[NSNumber numberWithInt:WWANReceived], nil];
}
+ (UIViewController *)fetchCurrentViewController{
    UIViewController *resultVC;
    resultVC = [self currentViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self currentViewController:resultVC.presentedViewController];
    }
    return resultVC;
}
+ (UIViewController *)currentViewController:(UIViewController *)viewController {
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        return [Tool currentViewController:[(UINavigationController *)viewController topViewController]];
    } else if ([viewController isKindOfClass:[UITabBarController class]]) {
        return [Tool currentViewController:[(UITabBarController *)viewController selectedViewController]];
    } else {
        return viewController;
    }
    return nil;
}
+ (NSString*)getUUID
{
    return [[[UIDevice currentDevice] identifierForVendor]UUIDString];
}
+(void)addLoginViewShow:(UIViewController *)controller
{
    [self addLoginViewShow:controller success:^{
    }];
}
+(void)addLoginViewShow:(UIViewController *)controller success:(void (^)(void))block
{
//    LoginController *loginVC = [[LoginController alloc] initWithNibName:@"LoginController" bundle:nil];
//    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVC];
//    loginVC.loginSuccess = ^{
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"finishRegistered" object:nil];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"HomeRequest" object:nil];
//        block();
//    };
//    [controller presentViewController:nav animated:NO completion:nil];
}

- (void)showActionSheetInView:(UIView *) view latitude:(CGFloat) latitude longitude:(CGFloat) longitude{
    CLLocationCoordinate2D dondinte;
    dondinte.latitude = latitude;
    dondinte.longitude = longitude;
    NSMutableArray *arrT = [NSMutableArray array];
    [self.maps removeAllObjects];
    NSArray *arr = [self getInstalledMapAppWithEndLocation:dondinte];
    if (arr != nil && arr.count != 0) {
        for (int i = 0; i<arr.count; i++) {
            [arrT addObject:[arr[i] objectForKey:@"title"]];
        }
    }
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    for (NSString *strTitle in arrT) {
        [sheet addButtonWithTitle:strTitle];
    }
    [sheet showInView:view];
}
#pragma mark    -   UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != -1) {
        if (buttonIndex == 1) {
            NSDictionary *dic = self.maps[0];
            [self navAppleMapLatitude:[dic[@"lat"] floatValue] longitude:[dic[@"lng"] floatValue]];
            return;
        }else if(buttonIndex == 0)
        {
        }else
        {
            NSDictionary *dic = self.maps[buttonIndex-1];
            NSString *urlString = dic[@"url"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        }
    }
}

#pragma mark - 导航方法
- (NSArray *)getInstalledMapAppWithEndLocation:(CLLocationCoordinate2D)endLocation
{
    //苹果地图
    NSMutableDictionary *iosMapDic = [NSMutableDictionary dictionary];
    iosMapDic[@"title"] = @"苹果地图";
    iosMapDic[@"lat"] = [NSString stringWithFormat:@"%f",endLocation.latitude];
    iosMapDic[@"lng"] = [NSString stringWithFormat:@"%f",endLocation.longitude];
    [self.maps addObject:iosMapDic];
    
    //百度地图
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        NSMutableDictionary *baiduMapDic = [NSMutableDictionary dictionary];
        baiduMapDic[@"title"] = @"百度地图";
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=北京&mode=driving&coord_type=gcj02",endLocation.latitude,endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        baiduMapDic[@"url"] = urlString;
        [self.maps addObject:baiduMapDic];
    }
    //高德地图
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        NSMutableDictionary *gaodeMapDic = [NSMutableDictionary dictionary];
        gaodeMapDic[@"title"] = @"高德地图";
        NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",@"导航功能",@"nav123456",endLocation.latitude,endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        gaodeMapDic[@"url"] = urlString;
        [self.maps addObject:gaodeMapDic];
    }
    
    //腾讯地图
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"qqmap://"]]) {
        NSMutableDictionary *qqMapDic = [NSMutableDictionary dictionary];
        qqMapDic[@"title"] = @"腾讯地图";
        NSString *urlString = [[NSString stringWithFormat:@"qqmap://map/routeplan?from=我的位置&type=drive&tocoord=%f,%f&to=终点&coord_type=1&policy=0",endLocation.latitude, endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        qqMapDic[@"url"] = urlString;
        [self.maps addObject:qqMapDic];
    }
    return self.maps;
}
//苹果地图
- (void)navAppleMapLatitude:(CGFloat) latitude longitude:(CGFloat) longitude
{
    CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(latitude,longitude);
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:loc addressDictionary:nil]];
    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                   launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
                                   MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
}



//-(NSMutableArray *)orderStatusArr{
//    if (!_orderStatusArr) {
//        _orderStatusArr = [NSMutableArray array];
//    }
//    return _orderStatusArr;
//}

- (void)initializeOrderStatus{
//    [[SHCRequestObj defaultsRequest] UrlRequrstGet:@"orderStatus/getOrderStatus" requestDic:nil returnObj:^(id obj) {
//        NSArray *array = obj[@"data"];
//
//        for (int i = 0; i <array.count; i++) {
//            OrderStatusModel *model = [OrderStatusModel mj_objectWithKeyValues:array[i]];
//            [self.orderStatusArr addObject:model];
//        }
//    } returnError:^(id error) {
//
//    }];
}

-(NSString *)getOrderStatusWithType:(int)type andSubType:(int)subType{
//    if (self.orderStatusArr.count == 0) {
//        [self initializeOrderStatus];
//    }
//    for (OrderStatusModel* model in self.orderStatusArr) {
//        if (model.type == type) {
//            for (orderStatusDetails *obj in model.orderStatusDetails) {
//                if (obj.subtype == subType) {
//                    return obj.desc;
//                }
//            }
//        }
//    }
    return nil;
}
// 检测网络状况
+ (void)exitNetwork{
    
//    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
//    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
//    __block   BOOL network =  NO;  //
//    __block   BOOL change =  NO;  //
//    
//    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
//     {
//         switch (status) {
//             case AFNetworkReachabilityStatusNotReachable:
//             {
//                 NSLog(@"无网络");
//                 SHC_ALERT_SHOW(@"无网络");
//                 network = NO;
//                 change = YES;
//                 break;
//             }
//                 
//             case AFNetworkReachabilityStatusReachableViaWiFi:
//             {
//                 NSLog(@"WiFi网络");
//                 SHC_ALERT_SHOW(@"WiFi网络");
//                 network = YES;
//                 change = YES;
//                 break;
//             }
//                 
//             case AFNetworkReachabilityStatusReachableViaWWAN:
//             {
//                 NSLog(@"无线网络");
//                 SHC_ALERT_SHOW(@"无线网络");
//                 network = YES;
//                 change = YES;
//                 break;
//             }
//                 
//             default:
//                 break;
//         }
//     }];
}
/**
 通过url中的width宽 height高 获取图片高度
 
 @param urlString 带参数的url
 
 @return float 高
 
 */
+ (float)toolImgHeightParamsWithUrlString:(NSString*)urlString
{
    NSDictionary *dic = [self toolGetParamsWithUrlString:urlString];
    NSString *widthStr = dic[@"width"];
    NSString *heightStr = dic[@"height"];
    float width = [widthStr isEqualToString:@""]?0:widthStr.floatValue;
    float height = [heightStr isEqualToString:@""]?0:heightStr.floatValue;
    //获取比例
    float proportion = width/height;
    //屏幕宽度除获取到的比例算出图片高度
    return SCREEN_WIDTH/proportion;
}
+ (float)toolImgHeightParamsWithUrlString:(NSString*)urlString imgWidth:(CGFloat)imgWidth
{
    NSDictionary *dic = [self toolGetParamsWithUrlString:urlString];
    NSString *widthStr = dic[@"width"];
    NSString *heightStr = dic[@"height"];
    float width = [widthStr isEqualToString:@""]?0:widthStr.floatValue;
    float height = [heightStr isEqualToString:@""]?0:heightStr.floatValue;
    //获取比例
    float proportion = width/height;
    return imgWidth/proportion;
}

/**
 获取url中的参数并返回
 @param urlString 带参数的url
 @return NSDictionary:参数字典
 */

+ (NSDictionary*)toolGetParamsWithUrlString:(NSString*)urlString
{
    NSArray*allElements = [urlString componentsSeparatedByString:@"?"];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];//待set的参数字典
    if (allElements.count==2) {
        NSString*paramsString = allElements[1];
        //获取参数对
        NSArray*paramsArray = [paramsString componentsSeparatedByString:@"&"];
        if(paramsArray.count>=1) {
            for(int i= 0; i < paramsArray.count; i++) {
                NSString*singleParamString = paramsArray[i];
                NSArray*singleParamSet = [singleParamString componentsSeparatedByString:@"="];
                if(singleParamSet.count==2) {
                    NSString*key = singleParamSet[0];
                    NSString*value = singleParamSet[1];
                    if(key.length>0|| value.length>0) {
                        [params setObject:value.length>0?value:@""forKey:key.length>0?key:@""];
                    }
                }
            }
        }
        return params;
        
    }else
    {
        NSLog(@"链接不包含参数！");
        return @{};
    }
}

+ (BOOL)isUrlAddress:(NSString*)url{
    NSString*reg =@"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSPredicate*urlPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
    return[urlPredicate evaluateWithObject:url];
}

// 判断用户是否允许接收通知
+ (BOOL)isUserNotificationEnable {
    BOOL isEnable = NO;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0f) { // iOS版本 >=8.0 处理逻辑
        UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
        isEnable = (UIUserNotificationTypeNone == setting.types) ? NO : YES;
    } else { // iOS版本 <8.0 处理逻辑
        UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        isEnable = (UIRemoteNotificationTypeNone == type) ? NO : YES;
    }
    return isEnable;
}

// 如果用户关闭了接收通知功能，该方法可以跳转到APP设置页面进行修改  iOS版本 >=8.0 处理逻辑
+ (void)goToAppSystemSetting {
    UIApplication *application = [UIApplication sharedApplication];
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([application canOpenURL:url]) {
        if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
            if (@available(iOS 10.0, *)) {
                [application openURL:url options:@{} completionHandler:nil];
            } else {
                // Fallback on earlier versions
            }
        } else {
            [application openURL:url];
        }
    }
}
//根据当前所在控制器push方法进行pop
+ (void)popOrdissmissMethod
{
//    if ([LFUntils fetchCurrentViewController].navigationController.topViewController == [LFUntils fetchCurrentViewController]) {
//        [[LFUntils fetchCurrentViewController].navigationController popViewControllerAnimated:YES];
//    } else {
//        [[LFUntils fetchCurrentViewController] dismissViewControllerAnimated:YES completion:nil];
//    }
}
@end












